package com.example.authserver.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.authserver.entity.TUser;
import com.example.authserver.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.annotation.Resources;
import java.util.List;
import java.util.Objects;

@Service
@Slf4j
public class MyUserDetailsServiceImpl implements UserDetailsService {
    @Resource
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        TUser user = userMapper.selectOne(new LambdaQueryWrapper<TUser>().eq(TUser::getUsername,username));
        if (Objects.isNull(user)) {
            throw new UsernameNotFoundException(username + "账户不存在");
        }
        List<String> permissions = userMapper.findAllPermissions(user.getId());
        String[] array = null;
        if (CollectionUtils.isEmpty(permissions)) {
            log.warn("{}无任何权限",user.getUsername());
            array = new String[]{};
        }else{
            array = new String[permissions.size()];
            permissions.toArray(array);
        }
        System.err.println(JSONObject.toJSONString(permissions,true));
        return User.withUsername(user.getUsername()).password(user.getPassword()).authorities(array).build();
    }
}
